const app = getApp();
const MAX_COUNT_IMAGE = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authLocationTips: false,
    pageType: 1, // 1添加 2编辑
    equipment_name: "",
    equipmentTypes: [], //设备类型
    equipmentTypeIndex: "",
    equipment_number: "", //设备编号
    villages: [],
    villageIndex: "",
    address: "",
    latitude: "",
    longitude: "",
    all_url_arrs: [],
    url_arrs: [],
    max_count_img: MAX_COUNT_IMAGE,
    partners: [], //所属合伙人
    partnerIndex: '', //选择的合伙人index
  },


  pickPartner(e) {
    const index = e.detail.value;
    console.log(this.data.partners[index])
    this.getPartnerOfVillage(this.data.partners[index].id);
    this.setData({
      partnerIndex: index,
      villageIndex: "",
      address: "",
      longitude: "",
      latitude: "",
    })
  },

  scanCode() {
    app.scanDeviceCode().then(res => {
      this.setData({
        equipment_number: res
      })
    });
  },

  getPartnerOfVillage(partner_id) {
    app.ajax({
      url: "Manage/Equipment/repairPersonnelPark",
      data: {
        partner_id
      },
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            villages: res.data.data[0].villageData
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },


  pickVillage(e) {
    const name = e.currentTarget.dataset.name;
    const villages = this.data.villages;
    const value = e.detail.value;
    console.log(villages[value]);
    this.setData({
      [name]: value,
      address: villages[value].address,
      longitude: villages[value].lng,
      latitude: villages[value].lat,
    })
  },

  //获取获取工程人员所属合伙人
  getCurrentRolePartner() {
    app.ajax({
      url: "",
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            partners: res.data.data
          })
        }
      }
    })
  },


  navMapSetting() {
    if (this.data.villageIndex === "") {
      app.showToast("请先选择园区", "none", 2000, function () {});
      return;
    }
    wx.getSetting({
      success: settingRes => {
        if (settingRes.errMsg === "getSetting:ok") {
          const setting = settingRes.authSetting;
          if (setting["scope.userLocation"] == undefined || setting["scope.userLocation"]) {
            if (!this.data.latitude || !this.data.longitude) {
              wx.getLocation({
                type:"gcj02",
                success: results => {
                  this.setData({
                    latitude: results.latitude,
                    longitude: results.longitude
                  })
                  this.openLocation();
                },
                fail: res => {
                  app.showToast("请检查是否打开手机定位功能");
                }
              })
            } else {
              this.openLocation();
            }
          } else if (setting["scope.userLocation"] == false) {
            this.setData({
              authLocationTips: true
            })
          }
        }
      },
      fail: e => {
        app.showToast("getSetting fail");
      }

    })
  },

  openLocation() {
    wx.chooseLocation({
      latitude: this.data.latitude - 0,
      longitude: this.data.longitude - 0,
      success: res => {
        if (res.errMsg === "chooseLocation:ok") {
          this.setData({
            address: res.name,
            longitude: res.longitude,
            latitude: res.latitude
          })
        }
        console.log(res, "results")
      },
      fail: e => {
        if (e.errMsg === "chooseLocation:fail auth deny") {
          this.setData({
            authLocationTips: true
          })
        }
      }
    })
  },

  handleOpenSetting() {
    wx.openSetting({
      success: res => {
        if (res.errMsg === "openSetting:ok") {
          if (res.authSetting["scope.userLocation"]) {
            this.setData({
              authLocationTips: false
            })
            this.openLocation()
          }
        }
      },
      fail: e => {
        app.showToast("打开设置失败");
      }
    })
  },


  closeLocationTips() {
    this.setData({
      authLocationTips: false
    })
  },

  handlePicker(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getCurrentRolePartner();
    this.getElementType();
  },


  //扫描二维码
  scan: function () {
    app.scanDeviceCode(true).then(res => {
      this.setData({
        equipment_number: res
      })
    }).catch(error => {
      app.showToast(error)
    })
  },
  //获取
  formSubmit: function (e) {
    const formVal = e.detail.value;
    if (formVal.equipment_number == '') {
      app.showToast("设备编号不能为空");
      return false;
    } else if (this.data.partnerIndex === '') {
      app.showToast("请选择合伙人");
      return false;
    } else if (formVal.equipment_name == '') {
      app.showToast("设备名不能为空");
      return false;
    } else if (this.data.equipmentTypeIndex === '') {
      app.showToast("请选择设备类型");
      return false;
    } else if (this.data.villageIndex === '') {
      app.showToast("请选择园区");
      return false;
    } else if (formVal.address == '') {
      app.showToast("请填写安装地址");
      return false;
    } else if (!this.data.latitude || !this.data.longitude) {
      app.showToast("请点击定位图标定位", 'none', 3000);
      return false;
    }
    let village = this.data.villages[this.data.villageIndex];
    wx.showLoading({
      mask: true,
    })

    app.ajax({
      url: "Manage/Equipment/addEquipment",
      data: {
        equipment_number: formVal.equipment_number,
        s_number: this.data.partners[this.data.partnerIndex].s_number,
        equipment_name: formVal.equipment_name,
        province: village.province,
        city: village.city,
        area: village.area,
        province_name: village.province_name,
        city_name: village.city_name,
        area_name: village.area_name,
        village_name: village.village_name,
        address: formVal.address,
        longitude: this.data.longitude,
        latitude: this.data.latitude,
        equipment_type: this.data.equipmentTypes[this.data.equipmentTypeIndex].id,
        equipment_img: this.data.url_arrs,
      },
      success: res => {
        wx.hideLoading();
        if (res.data.code == 1000) {
          app.showToast(res.data.messagem, "success");
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误");
      }
    })
  },


  //获取设备类型
  getElementType: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getEquipmentType',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          var data = res.data.data;
          that.setData({
            equipmentTypes: data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },



  chooseImg() {
    let pictrues = this.data.all_url_arrs;
    let count = MAX_COUNT_IMAGE - pictrues.length;
    wx.chooseImage({
      count,
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '资源上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          this.uploadFile(tempFilePaths[i], i, tempFilePaths.length - 1);
        }
      }
    })
  },

  uploadFile: function (tempFilePath, i, len) {
    var that = this;
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePath,
      name: 'file',
      success(res) {
        var source = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
        if (source.code == 1000) {
          let all_url_arrs = that.data.all_url_arrs;
          let url_arrs = that.data.url_arrs;
          url_arrs.unshift(source.data.url);
          all_url_arrs.unshift(source.data.all_url);
          console.log(all_url_arrs, url_arrs);
          if (i == len) {
            wx.hideLoading();
          }
          that.setData({
            all_url_arrs,
            url_arrs
          })
        } else {
          app.showToast(`第${i+1}张图片上传失败`);
        }
      }
    })
  },

  deleteImg(e) {
    const index = e.currentTarget.dataset.index;
    let all_url_arrs = this.data.all_url_arrs;
    let url_arrs = this.data.url_arrs;
    all_url_arrs.splice(index, 1)
    url_arrs.splice(index, 1)
    this.setData({
      all_url_arrs,
      url_arrs
    })
  },


})